package cn.tedu.product.service;

import cn.tedu.product.mapper.ProductMapper;

import com.fasterxml.jackson.core.JsonProcessingException;

import com.fasterxml.jackson.databind.ObjectMapper;


import com.jt.common.pojo.Product;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;

import org.elasticsearch.action.index.IndexRequestBuilder;

import org.elasticsearch.client.IndicesAdminClient;

import org.elasticsearch.client.transport.TransportClient;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;


import java.util.List;

@Service
public class IndexService {
    @Autowired(required = false)
    private ProductMapper productMapper;
    @Autowired(required = false)
    private TransportClient client;
    private static final ObjectMapper mapper=new ObjectMapper();
    public void createIndex() throws JsonProcessingException {
        //拿到管理索引的对象
        IndicesAdminClient indices = client.admin().indices();
        String indexName="easymall";
        String typeName = "product";
        IndicesExistsResponse response = indices.prepareExists("easymall").get();
        //判断索引是否存在
        if(!response.isExists()){
            indices.prepareCreate(indexName).get();
        }
        //读取数据
        List<Product> products = productMapper.selectProductByPage(0, 100);
        for (Product product: products
             ) {
            String doc = mapper.writeValueAsString(product);
            IndexRequestBuilder request = client.prepareIndex(indexName, typeName, product.getProductId());
            request.setSource(doc).get();
        }
    }
}
